# -*- codeing = utf-8 -*-

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse, redirect
from user import models
from django.conf import settings
import datetime


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """
        请求来的时候需要经过每一个中间件里面的process_request方法，
        按照注册顺序由上到下
        :param request:
        :return:若返回HttpResponse对象后将不再往后执行请求，会原路返回
        """
        user_id = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer = user_obj
        # return HttpResponse('若返回HttpResponse对象后将不再往后执行请求，会原路返回')

        # 白名单：没有登录都可以访问固定的URL
        if request.path in settings.WHITE_REGEX_URL_LIST:
            return
        # 非白名单url，检查用户是否登录，未登录跳转到登录页面
        if not request.tracer:
            return redirect(settings.WHITE_REGEX_URL_LIST[0])

        # 登录之后，访问后台管理时，获取当前用户拥有的额度：
        # 方式1：免费额度在交易记录中存储
        '''
        trans_obj = models.Transaction.objects.filter(user=user_obj,status=2).order_by('-id').first()
        # 有交易记录且已过期，重新赋值
        current_date = datetime.datetime.now()
        if trans_obj and trans_obj.end_datetime < current_date:
            trans_obj = models.Transaction.objects.filter(user=user_obj,status=2,price_policy__category=1).first()
        request.price_policy = trans_obj.price_policy
        # print(request.price_policy)
        '''
        # 方式2：免费的额度存储在配置文件
        # trans_obj = models.Transaction.objects.filter(user=user_obj, status=2, ).order_by('-id').first()
        # if not trans_obj:
        #     request.price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        # else:
        #     current_date = datetime.datetime.now()
        #     if trans_obj.end_datetime < current_date:
        #         request.price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        #     else:
        #         request.price_policy = trans_obj.price_policy  # trans_obj.price_policy 一对多：正向查询

    def process_response(self, request, response):
        """
        响应走的时候需要经过每一个中间件里的process_response方法，该方法包括request和response两个参数，
        按照注册顺序由下到上
        :return:
        """
        return response  # 1、返回默认的响应内容
        # return HttpResponse('也可以返回自定义内容')     #2、也可以返回自定义内容

    # def process_view(self, request, view_name, args, kwargs):
    #
    #     request.project = None
    #     # 1、判断项目URL是否以manage开头，如果是则判断是否为我创建or参与
    #     if not request.path_info.startswith('/web/manage/'):
    #         return
    #     # 2、判断是否为我创建or参与
    #     project_id = kwargs.get('project_id')
    #     # print(kwargs)      # {'project_id': '11'}
    #     # print(args)
    #     project_obj = models.Project.objects.filter(creator=request.tracer, id=project_id).first()
    #     if project_obj:
    #         request.project = project_obj
    #         return
    #     project_user_obj = models.ProjectUser.objects.filter(user=request.tracer, project_id=project_id).first()
    #     if project_user_obj:
    #         request.project = project_user_obj.project
    #         return
    #     return redirect('web:project_list')
